#!/bin/bash

# Docker服务管理脚本
# 支持批量或单独管理服务: mysql, nacos, redis
# 用法: ./services.sh [action] [service_name]
# action: start|stop|restart|status
# service_name: all|mysql|nacos|redis (可选，默认为all)

set -e

# 脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 定义服务列表
ALL_SERVICES="mysql nacos redis gitlab"

# 获取服务对应的目录
get_service_dir() {
    local service=$1
    case $service in
        "mysql") echo "mysql" ;;
        "nacos") echo "nacos" ;;
        "redis") echo "redis" ;;
        "gitlab") echo "gitlab" ;;
        *) return 1 ;;
    esac
}

# 检查服务是否有效
is_valid_service() {
    local service=$1
    case $service in
        mysql|nacos|redis|gitlab) return 0 ;;
        *) return 1 ;;
    esac
}

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查docker和docker-compose是否安装
check_dependencies() {
    if ! command -v docker &> /dev/null; then
        log_error "Docker is not installed or not in PATH"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null 2>&1; then
        log_error "Docker Compose is not installed or not in PATH"
        exit 1
    fi
}

# 获取docker-compose命令
get_docker_compose_cmd() {
    if command -v docker-compose &> /dev/null; then
        echo "docker-compose"
    else
        echo "docker compose"
    fi
}

# 检查服务目录是否存在
check_service_dir() {
    local service=$1
    
    if ! is_valid_service "$service"; then
        log_error "Unknown service: $service"
        return 1
    fi
    
    local service_subdir=$(get_service_dir "$service")
    local service_dir="${SCRIPT_DIR}/${service_subdir}"
    
    if [[ ! -d "$service_dir" ]]; then
        log_error "Service directory does not exist: $service_dir"
        return 1
    fi
    
    if [[ ! -f "$service_dir/docker-compose.yml" ]]; then
        log_error "docker-compose.yml not found in: $service_dir"
        return 1
    fi
    
    return 0
}

# 执行docker-compose操作
execute_docker_compose() {
    local action=$1
    local service=$2
    local service_subdir=$(get_service_dir "$service")
    local service_dir="${SCRIPT_DIR}/${service_subdir}"
    local compose_cmd=$(get_docker_compose_cmd)
    
    log_info "Executing $action for service: $service"
    
    cd "$service_dir"
    
    case $action in
        "start")
            $compose_cmd up -d
            ;;
        "stop")
            $compose_cmd down
            ;;
        "restart")
            $compose_cmd down
            sleep 2
            $compose_cmd up -d
            ;;
        "status")
            $compose_cmd ps
            ;;
        *)
            log_error "Unknown action: $action"
            return 1
            ;;
    esac
    
    if [[ $? -eq 0 ]]; then
        log_success "$action completed for service: $service"
    else
        log_error "$action failed for service: $service"
        return 1
    fi
}

# 获取服务状态
get_service_status() {
    local service=$1
    local service_subdir=$(get_service_dir "$service")
    local service_dir="${SCRIPT_DIR}/${service_subdir}"
    local compose_cmd=$(get_docker_compose_cmd)
    
    cd "$service_dir"
    
    # 检查容器是否运行
    local containers=$($compose_cmd ps -q 2>/dev/null | wc -l | tr -d ' ')
    if [[ $containers -gt 0 ]]; then
        local running=$($compose_cmd ps 2>/dev/null | grep -c "Up" || echo "0")
        if [[ $running -gt 0 ]]; then
            echo "running"
        else
            echo "stopped"
        fi
    else
        echo "not_created"
    fi
}

# 处理单个服务
handle_service() {
    local action=$1
    local service=$2
    
    if ! is_valid_service "$service"; then
        log_error "Unknown service: $service"
        log_info "Available services: $ALL_SERVICES"
        return 1
    fi
    
    if ! check_service_dir "$service"; then
        return 1
    fi
    
    case $action in
        "status")
            local status=$(get_service_status "$service")
            printf "%-10s: %s\n" "$service" "$status"
            ;;
        *)
            execute_docker_compose "$action" "$service"
            ;;
    esac
}

# 处理所有服务
handle_all_services() {
    local action=$1
    local failed_services=()
    
    log_info "Executing $action for all services..."
    
    for service in $ALL_SERVICES; do
        if ! check_service_dir "$service"; then
            log_warn "Skipping service: $service"
            continue
        fi
        
        case $action in
            "status")
                local status=$(get_service_status "$service")
                printf "%-10s: %s\n" "$service" "$status"
                ;;
            *)
                if ! execute_docker_compose "$action" "$service"; then
                    failed_services+=("$service")
                fi
                ;;
        esac
        
        # 在服务操作之间添加短暂延迟
        if [[ $action != "status" ]]; then
            sleep 1
        fi
    done
    
    if [[ ${#failed_services[@]} -gt 0 ]]; then
        log_error "Failed services: ${failed_services[*]}"
        return 1
    else
        if [[ $action != "status" ]]; then
            log_success "All services $action completed successfully"
        fi
    fi
}

# 显示帮助信息
show_help() {
    cat << EOF
Docker服务管理脚本

用法:
    $0 <action> [service_name]

参数:
    action       操作类型: start|stop|restart|status
    service_name 服务名称: all|mysql|nacos|redis|gitlab (可选，默认为all)

示例:
    $0 start              # 启动所有服务
    $0 start mysql        # 启动MySQL服务
    $0 stop               # 停止所有服务
    $0 restart nacos      # 重启Nacos服务
    $0 status             # 查看所有服务状态
    $0 status redis       # 查看Redis服务状态

支持的服务:
$(echo "$ALL_SERVICES" | tr ' ' '\n' | sed 's/^/    /')
EOF
}

# 主函数
main() {
    # 检查依赖
    check_dependencies
    
    # 解析参数
    local action=${1:-}
    local service=${2:-all}
    
    # 验证action参数
    if [[ -z "$action" ]]; then
        log_error "Action parameter is required"
        show_help
        exit 1
    fi
    
    case $action in
        "start"|"stop"|"restart"|"status")
            ;;
        "help"|"-h"|"--help")
            show_help
            exit 0
            ;;
        *)
            log_error "Invalid action: $action"
            show_help
            exit 1
            ;;
    esac
    
    # 执行操作
    if [[ "$service" == "all" ]]; then
        handle_all_services "$action"
    else
        handle_service "$action" "$service"
    fi
}

# 执行主函数
main "$@" 